package cn.xdwanj.config

import com.alibaba.druid.pool.DruidDataSource
import com.google.gson.Gson
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.*
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.transaction.annotation.EnableTransactionManagement
import org.springframework.web.servlet.view.InternalResourceViewResolver
import javax.sql.DataSource

@Configuration
@Import(
  SpringWebConfig::class,
  MyBatisConfig::class
)
@ComponentScan("cn.xdwanj")
@PropertySource("classpath:db.properties")
@EnableAspectJAutoProxy
@EnableTransactionManagement
open class SpringRootConfig {

  @Bean
  open fun moshi(): Moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()

  @Bean
  open fun gson(): Gson = Gson()

  @Bean
  open fun druidDataSource(
    @Value("\${driver}") driver: String,
    @Value("\${url}") url: String,
    @Value("\${user}") username: String,
    @Value("\${password}") password: String
  ) = DruidDataSource().apply {
    this.driverClassName = driver
    this.url = url
    this.username = username
    this.password = password
  }

  @Bean
  open fun jdbcTemplate(
    dataSource: DataSource
  ) = JdbcTemplate().apply {
    this.dataSource = dataSource
  }

  @Bean
  open fun transactionManager(
    dataSource: DataSource
  ) = DataSourceTransactionManager(dataSource)

  @Bean
  open fun resourceViewResolver() = InternalResourceViewResolver().apply {
    this.setPrefix("/WEB-INF/pages/")
    this.setSuffix(".html")
  }
}